package com.doubao.notepad_blog_backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.doubao.notepad_blog_backend.common.exception.ApiAsserts;
import com.doubao.notepad_blog_backend.domain.BmsPost;
import com.doubao.notepad_blog_backend.domain.BmsPostTag;
import com.doubao.notepad_blog_backend.domain.BmsTag;
import com.doubao.notepad_blog_backend.domain.UmsUser;
import com.doubao.notepad_blog_backend.dto.CreatePostDTO;
import com.doubao.notepad_blog_backend.mapper.BmsPostMapper;
import com.doubao.notepad_blog_backend.mapper.BmsTagMapper;
import com.doubao.notepad_blog_backend.service.BmsPostService;
import com.doubao.notepad_blog_backend.service.BmsPostTagService;
import com.doubao.notepad_blog_backend.service.BmsTagService;
import com.doubao.notepad_blog_backend.service.UmsUserService;
import com.doubao.notepad_blog_backend.vo.PostVO;
import com.doubao.notepad_blog_backend.vo.ProfileVO;
import com.vdurmont.emoji.EmojiParser;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

@Service
public class BmsPostServiceImpl extends ServiceImpl<BmsPostMapper, BmsPost> implements BmsPostService {

    @Resource
    private BmsPostMapper postMapper;

    @Resource
    private UmsUserService userService;

    @Resource
    private BmsTagMapper tagMapper;

    @Resource
    private BmsTagService tagService;

    @Resource
    private BmsPostTagService postTagService;


    public Page<PostVO> getList(Integer pageNo, Integer pageSize, String tab) {
        Page<PostVO> page = new Page( pageNo, pageSize );
        // 查询文章
        Page<PostVO> iPage = postMapper.selectListAndPage( page, tab );
        return iPage;
    }

    /**
     * 保存文章
     *
     * @param userName
     * @param createPostDTO
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public BmsPost createPost(String userName, CreatePostDTO createPostDTO) {
        // 获取用户
        UmsUser loginUser = userService.getOne(
                new LambdaQueryWrapper<UmsUser>().eq( UmsUser::getUsername, userName )
        );
        if (ObjectUtils.isNull( loginUser )) {
            ApiAsserts.fail( "用户不存在" );
        }

        // 保存
        BmsPost post = BmsPost.builder()
                .userId( loginUser.getId() )
                .title( createPostDTO.getTitle() )
                .content( createPostDTO.getContent() )
                .createTime( new Date() )
                .build();
        this.save( post );
        // 给用户增加积分+1
        userService.updateById( loginUser.setScore( loginUser.getScore() + 1 ) );

        // 保存标签(先查询是否存在)
        for (String tag : createPostDTO.getTags()) {
            BmsTag bmsTag = tagMapper.selectOne(
                    new LambdaQueryWrapper<BmsTag>().eq( BmsTag::getName, tag )
            );
            //如果不存在，保存
            if (ObjectUtils.isNull( bmsTag )) {
                bmsTag = new BmsTag();
                bmsTag.setName( tag );
                bmsTag.setPostCount( 1 );
                tagMapper.insert( bmsTag );
                System.out.println( "bmsTag = " + bmsTag );
            } else {// 否存 + 1
                tagMapper.updateById( bmsTag.setPostCount( bmsTag.getPostCount() + 1 ) );
            }
            // 保存post_tag
            System.out.println( "post.getId() = " + post.getId() );
            System.out.println( "bmsTag.getId() = " + bmsTag.getId() );
            postTagService.save( BmsPostTag.builder().postId( post.getId() ).tagId( bmsTag.getId() ).build() );

        }
        return post;
    }

    /**
     * 获取文章
     *
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> getPostById(String id) {
        HashMap<String, Object> map = new HashMap<>( 16 );
        // 查询文章
        BmsPost post = this.getById( id );
        Assert.notNull( post, "当前文章不存在，或被删除" );
        // 查看 +1
        post.setView( post.getView() + 1 );
        this.updateById( post );
        // 表情转码
        post.setContent( EmojiParser.parseToUnicode( post.getContent() ) );
        map.put( "post", post );
        // 文章的标签
        // 标签
        QueryWrapper<BmsPostTag> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq( BmsPostTag::getPostId, post.getId() );
        Set<String> set = new HashSet<>();
        for (BmsPostTag articleTag : postTagService.list( wrapper )) {
            set.add( articleTag.getTagId() );
        }
        List<BmsTag> tags = tagService.listByIds( set );
        map.put( "tags", tags );

        // 作者
        ProfileVO user = userService.getUserProfile( post.getUserId() );
        map.put( "user", user );

        return map;
    }

    /**
     * 随机文章
     *
     * @param id
     * @return
     */
    @Override
    public List<BmsPost> getRecommend(String id) {
        List<BmsPost> recommend = postMapper.getRecommend( id );
        return recommend;
    }

    public BmsPost updateById(String userName, BmsPost post) {
        // 获取用户信息
        UmsUser umsUser = userService.getOne( new LambdaQueryWrapper<UmsUser>().eq( UmsUser::getUsername, userName ) );
        Assert.notNull( umsUser, "用户不存在" );
        Assert.isTrue( umsUser.getId().equals( post.getUserId() ), "非本人无权修改" );
        post.setModifyTime( new Date() );
        post.setContent( EmojiParser.parseToAliases( post.getContent() ) );
        this.updateById( post );
        return post;
    }

    public void deleteById(String userName, String id) {
        UmsUser umsUser = userService.getOne( new LambdaQueryWrapper<UmsUser>().eq( UmsUser::getUsername, userName ) );
        Assert.notNull( umsUser, "用户不存在" );
        BmsPost post = this.getById( id );
        Assert.notNull( post, "来晚一步，话题已不存在" );
        Assert.isTrue( post.getUserId().equals( umsUser.getId() ), "不可以删除别人的话题" );
        this.removeById( id );
    }

    @Override
    public Page<PostVO> searchByKey(String keyword, Page<PostVO> page) {
        // 查询话题
        Page<PostVO> iPage = this.baseMapper.searchByKey(keyword,page);
        return iPage;
    }


}
